<template>
  <div>
    <!--输入框-->
    <div class="input">
      <el-input v-model="keyword"
                placeholder="请输入培训师用户名"
                style="width:200px"
                clearable
                size="large"
      />
      <el-button type="primary" size="large" @click="list(1)">搜索</el-button>
      <el-button type="primary" size="large" @click="openDialog">创建培训师</el-button>
    </div>
    <el-dialog
        title="培训师创建"
        v-model="dialogVisible"
        width="400px"
        :closeOnClickModal="false"
        :show-close="false"
    >
      <el-form :model="form" label-width="auto" style="max-width: 600px" :rules="rules" ref="createForm">
        <el-form-item label="用户名" prop="createName" >
          <el-input v-model="form.createName"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone"/>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色" @change="selectRole">
            <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色内容">
          <el-input v-model="roleForm.content" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div class="f">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary" @click="create">创 建 </el-button>
          </div>
  </span>
    </el-dialog>
    <el-table :data="personDetail" style="width: 100%">
      <el-table-column prop="username" label="培训师用户名" width="300"/>
      <el-table-column prop="phone" label="电话" width="300"/>
      <el-table-column prop="lastLoginTime" label="最近登录时间"/>
      <el-table-column prop="name" label="公司">
      <template #default="scope">
        <el-tag  disable-transitions>{{scope.row.name}}</el-tag>
      </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button
              v-if="scope.row.identify===3 && scope.row.status!=='1'"
              size="small"
              type="primary"
              @click="revisePersonRole(scope.row)"
          >修改
          </el-button>
          <el-button v-if="scope.row.status!=='1'"
                     size="small"
                     :type="scope.row.status==='2'?'danger':'success'"
                     @click="revisePersonStatus(scope.row)"
          >
            {{scope.row.status==='2'?'禁用':'启用'}}
          </el-button>
          <div v-if="scope.row.status==='1'">等待激活</div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
        title="修改角色"
        v-model="roleVisible"
        width="380px"
        :show-close="false"
        :close-on-click-modal="false"
    >
      <el-form ref="form" :model="roleForm" label-width="80px" :rules="reviseRules">
        <el-form-item label="角色内容">
          <el-input v-model="roleForm.content" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-select v-model="roleForm.name" placeholder="请选择该公司其他培训师" @change="selectRole">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" style="margin-left: 30%">
    <el-button @click="cancelRole">取 消</el-button>
    <el-button type="primary" @click="reviseRole">确 定</el-button>
  </span>
    </el-dialog>

    <!--分页-->
    <Pagination ref="pagination" v-bind:list="list" v-bind:itemCount="8"></Pagination>


  </div>
</template>

<script>
import Pagination from '@/components/Pagination.vue'
import API from '@/api/manage'
import {JSEncrypt} from "jsencrypt";

export default {
  components: {
    Pagination
  },
  data() {
    return {
      cid:'',
      userRoleList:[],
      personDetail:[],
      roleVisible:false,
      roleForm:{
        content:'',
        name:''
      },
      keyword:'',
      options:[],
      dialogVisible:false,
      form: {
        createName: '',
        phone: '',
        roleId: ''
      },
      roleOptions:[],
      rules:{
        createName:[
          {required:true,message:'请输入培训师账号',trigger:'blur'}
        ],
        phone:[
          {required:true,message:'请输入培训师手机号',trigger:'blur'},
          {pattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
            ,message: '请输入正确的手机号',trigger: "blur"}
        ],
        roleId:[
          {required:true,message:'分配角色不能为空',trigger:'blur'}
        ],
      },
      reviseRules:{
        name:[
          {required:true,message:'请选择该公司其他培训师',trigger:'blur'}
        ],
      }
    }
  },
  mounted() {
    this.cid=localStorage.getItem('cid')
    let _this = this
    _this.$refs.pagination.size = 10
    localStorage.setItem('CURRENT_TRAINER_LIST_PAGE',1)
    let currentPage = localStorage.getItem('CURRENT_TRAINER_LIST_PAGE') || 1
    _this.list(currentPage)
  },
  methods: {
    // 创建培训师
    create(){
      this.$refs["createForm"].validate(valid=>{
        if(valid){
          API.getPublicKey().then((res) => {
            if (res.data.code === '0') {
              let params = {}
              const entry = new JSEncrypt()
              entry.setPublicKey(res.data.content.publicKeyStr)
              params.username = entry.encrypt(this.form.createName)
              params.phone = entry.encrypt(this.form.phone)
              params.role = entry.encrypt(this.form.roleId.toString())
              params.random = res.data.content.random
              params.identify = 3
              API.adminRegister(params).then((result) => {
                if (result.data.code === '0') {
                  this.$message.success('创建成功')
                  this.list(1)
                  this.cancel()
                }
              }).catch(err => {
                console.log(err)
              })
            }
          })
        }
      })
    },
    // 取消创建
    cancel() {
      this.dialogVisible = false;
      this.form = {};
      this.companyOptions = [];
      this.roleOptions = []
    },
// 查询公司角色
    querycompanyRole() {
      let token = localStorage.getItem('token')
      API.queryUserRole({
        cId: this.cid
      }, token).then(res => {
        if (res.data.content.records.length === 0) {
          this.roleOptions = [];
          this.form.roleId = ''
        } else {
          this.userRoleList=res.data.content.records.filter(item=>item.roleName.includes("培训师"))
          this.roleOptions = this.userRoleList.map(item => {
            return {
              value: item.id,
              label: item.roleName
            }
          })
          console.log(this.roleOptions,11)
        }
      }).catch(err => {
        console.log(err)
      })
    },

    // 打开创建培训师框
    openDialog() {
      this.dialogVisible = true
      this.querycompanyRole()
    },
    //确认修改角色
    reviseRole(){
      this.$refs["form"].validate(valid=>{
        if(valid){
          let token=localStorage.getItem('token')
          API.updateUserInfoOfRole({
            id:this.userId,
            role:this.roleForm.name
          },token).then(res=>{
            if(res.data===true){
              this.$message.success('修改成功！')
            }
          }).catch(err=>{
            console.log(err)
          })
          this.cancelRole()
        }
      })
    },
    //取消修改角色框
    cancelRole(){
      this.roleVisible = false
      this.roleForm={
        content:'',
        name:''
      }
    },
    //选择角色
    selectRole(id){
      this.roleForm.content=this.userRoleList.find(item => item.id === id).roleComent
    },

// 修改用户角色
    revisePersonRole(row){
      let token=localStorage.getItem('token')
      this.userId=row.id
      API.queryUserRole({
        id:row.role
      },token).then(res=>{
        if(res.data.success===true){
          API.queryUserRole({
            cId:res.data.content.records[0].cid
          },token).then(res1=>{
            if(res1.data.success===true){
              this.userRoleList=res1.data.content.records.filter(item=>item.roleName.includes("培训师"))
              this.options = this.userRoleList.map(item => {
                return {
                  value: item.id,
                  label: item.roleName
                }
              })
              this.roleVisible=true
            }
          }).catch(err1=>{
            console.log(err1)
          })
        }
      }).catch(err=>{
        console.log(err)
      })
    },
    //修改培训师状态
    revisePersonStatus(row){
      let token=localStorage.getItem('token')
      API.modifyUserStatus({
        id:row.id,
        status:row.status==='2'?'3':'2'
      },token).then(res=>{
        if(res.data.success===true){
          let currentPage = localStorage.getItem('CURRENT_TRAINER_LIST_PAGE')
          this.list(currentPage)
        }
      }).catch(err=>{
        console.log(err)
      })
    },


    /**
     * 人员查询
     * @param page
     */
    list(page) {
      localStorage.setItem('CURRENT_TRAINER_LIST_PAGE', page)
      let params = {}
      params.current = page
      params.size = this.$refs.pagination.size
      params.username = this.keyword.trim()
      params.identify = 3
      params.cid=this.cid
      let token = localStorage.getItem("token")
      API.getUser2({
        condition: params,
        paging: {
          pageIndex: params.current,
          pageSize: params.size
        }
      }, token).then(res => {
            this.personDetail = res.data.data
            this.totalCount = res.data.totalCount
            this.$refs.pagination.render(page, res.data.totalCount);
            for (let i = 0; i < this.personDetail.length; i++) {
              if (this.personDetail[i].lastLoginTime > 0) {
                this.personDetail[i].lastLoginTime = this.modifyTime(parseInt(res.data.data[i].lastLoginTime))
              } else {
                this.personDetail[i].lastLoginTime = '未激活'
              }
              if (this.personDetail[i].phone <= 0) {
                this.personDetail[i].phone = '未激活'
              }
            }
      }).catch(err => {
              console.log(err)
            })
          },
          //根据value找label
          findLabelByValue(value)
      {
        const foundObject = this.roleOptions.find(obj => obj.value === value);
        return foundObject ? foundObject.label : null;
      }
    ,

      modifyTime(milliseconds)
      {
        const date = new Date(milliseconds);
        // 获取年份、月份、日期等信息
        const year = date.getFullYear();
        const month = date.getMonth() + 1; // JavaScript中月份从0开始计算，所以需要加1
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();
        return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;

      }
    }
  }
</script>

<style scoped>
.input {
  padding-top: 5px;
}

.f {
  text-align: center;
}

.transfeLayout {
  margin-left: 120px;
  margin-bottom: 25px;

}

.transfeLayout >>> .el-transfer-panel {
  width: 300px;
}

.transfeTitle {
  width: 120px;
  height: 0px;
  padding-left: 12px;
  margin-bottom: 0px;
}

.exam-list {
  width: 100%;
}

.exam-list .col2-cell-style {
  color: #409EFF;
  cursor: pointer;
}
</style>